<template>
	<view class="home-page safe-container">
		<!-- 状态栏安全区域 -->
		<view class="status-bar-safe-area" :style="{ height: statusBarHeight + 'px' }"></view>

		<!-- Banner轮播 -->
		<view class="banner-swiper">
			<swiper class="swiper" indicator-dots :autoplay="true" :interval="3000" :duration="500" circular>
				<swiper-item v-for="(item, index) in banners" :key="index">
					<image :src="item.imageArray[0]" mode="aspectFill" class="banner-image"
						@click="goToNotice(item.noticeId)"></image>
				</swiper-item>
			</swiper>
		</view>

		<!-- 公告栏 -->
		<view class="notice-bar" style="margin-top: 20rpx;">
			<text class="notice-icon">📢</text>
			<view class="notice-content" :style="{ transform: `translateY(-${currentNoticeIndex * 100}%)` }">
				<view class="notice-item" v-for="(notice, index) in noticeList" :key="index"
					@click="goToNotice(notice.noticeId)">
					{{ notice.title }}
				</view>
			</view>
		</view>

		<!-- 快捷图标 -->
		<view class="quick-icons">
			<view class="icon-item" v-for="(item, index) in quickIcons" :key="index"
				@tap="handleQuickAction(item.action)">
				<view class="icon-circle" :style="{backgroundColor: item.bgColor}">
					<text class="iconfont" :style="{color: item.color}">{{ item.icon }}</text>
				</view>
				<text class="icon-text">{{ item.text }}</text>
			</view>
		</view>

		<!-- 社区帖子流 -->
		<view class="post-list">
			<view class="post-card" v-for="(post, index) in posts" :key="index" @tap="openPostDetail(post)">
				<!-- 图片区域 -->
				<view class="post-image-container" v-if="post.imageUrls && post.imageUrls.length > 0">
					<view class="single-image">
						<image :src="post.imageUrls[0]" mode="aspectFill" class="post-image"></image>
					</view>
					<view class="ai-badge">
						<text class="iconfont">🤖</text>
						<text class="badge-text">AI推荐</text>
					</view>
				</view>
				<view>
					<text class="title-info">{{post.title}}</text>
				</view>
				<!-- 信息区域 -->
				<view class="post-info">

					<view class="user-info">
						<image :src="post.avatarUrl" mode="aspectFill" class="avatar"
							@tap.stop="viewUserProfile(post.userIdStr)"></image>
						<view class="user-detail">
							<text class="username">{{post.nickName}}</text>
							<text class="post-time">{{ post.createTime }}</text>
						</view>
					</view>
					<view class="post-actions">
						<view class="action-item">
							<text class="iconfont">❤</text>
							<text class="action-text">{{ post.likeCount }}</text>
						</view>
						<view class="action-item" @tap.stop="handleComment(post)">
							<text class="iconfont">💬</text>
							<text class="action-text">{{ post.commentCount }}</text>
						</view>
					</view>
				</view>

				<!-- 底部安全区域 -->
				<view class="bottom-safe-area" :style="{ height: safeAreaBottom + 'px' }"></view>
			</view>
		</view>
		<!-- 新增的上方悬浮按钮 -->
		<view class="float-extra-btn" @tap="handleScrollToTop">
			<text class="iconfont">▲</text>
		</view>
		<!-- 悬浮添加按钮 -->
		<view class="float-add-btn" @tap="navigateToAddPost">
			<text class="iconfont">➕</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import userManager from '../../common/utils/user.js'
	import systemUtils from '../../common/utils/system.js'
	import {
		getAllPosts
	} from '@/api/post.js';
	import {
		onReachBottom,
		onLoad,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		getAllNotice
	} from '@/api/Notice.js'

	// 系统相关
	const statusBarHeight = ref(0)
	const safeAreaBottom = ref(0)

	// 轮播图数据
	const banners = ref([])

	// 公告相关
	const noticeList = ref([])
	const currentNoticeIndex = ref(0)
	let noticeTimer = null

	// 快捷图标数据
	const quickIcons = ref([{
			icon: '🏥',
			text: '健康管理',
			bgColor: '#FFD1DC20',
			color: '#FFD1DC',
			action: 'health'
		},
		{
			icon: '📅',
			text: '日程提醒',
			bgColor: '#89CFF020',
			color: '#89CFF0',
			action: 'schedule'
		},
		{
			icon: '📊',
			text: '数据分析',
			bgColor: '#B7F0AD20',
			color: '#B7F0AD',
			action: 'analysis'
		},
		{
			icon: '🏠',
			text: '寄养服务',
			bgColor: '#FFD1DC20',
			color: '#FFD1DC',
			action: 'foster'
		}
	])

	// 帖子相关
	const posts = ref([])
	const pageNum = ref(1)
	const pageSize = ref(5)
	const isLoading = ref(false)

	// 页面加载
	onLoad(async (options) => {
		uni.startPullDownRefresh(); // 触发下拉刷新
	})

	// 下拉刷新逻辑（所有系统通用）
	onPullDownRefresh(async () => {
		console.log('refresh');
		try {
			pageNum.value = 1
			const freshData = await getAllPosts(pageNum.value, pageSize.value)
			posts.value = freshData
		} catch (err) {
			console.error('下拉刷新失败', err)
		} finally {
			setTimeout(() => {
				uni.stopPullDownRefresh(); // 结束刷新动画
			}, 1000);
		}
	})

	// 页面挂载
	onMounted(async () => {
		statusBarHeight.value = systemUtils.getStatusBarHeight()
		safeAreaBottom.value = systemUtils.getSafeAreaBottom()
		posts.value = await getAllPosts(pageNum.value, pageSize.value)
		const notice = await getAllNotice()
		console.log(notice)
		banners.value = notice.filter(item => item.type === 1);
		noticeList.value = notice.filter(item => item.type === 2)
		checkLoginStatus()

		// 启动公告轮播
		startNoticeLoop()
	})

	// 页面显示
	onShow(async () => {
		pageNum.value = 1
		pageSize.value = 5
		posts.value = await getAllPosts(pageNum.value, pageSize.value)
	})

	// 上拉加载更多
	onReachBottom(async () => {
		if (isLoading.value) return
		isLoading.value = true;
		try {
			pageNum.value++;
			const res = await getAllPosts(pageNum.value, pageSize.value)
			console.log(res)
			if (res && res.length > 0) {
				posts.value = posts.value.concat(res)
			} else {
				pageNum.value--;
				return
			}
		} catch (err) {
			console.error('加载更多失败', err)
			pageNum.value--;
		} finally {
			isLoading.value = false
		}
	})

	// 页面卸载时清除定时器
	onUnmounted(() => {
		if (noticeTimer) {
			clearInterval(noticeTimer)
			noticeTimer = null
		}
	})

	// 公告轮播逻辑
	const startNoticeLoop = () => {
		if (noticeTimer) {
			clearInterval(noticeTimer)
		}

		// 每3秒切换一次公告
		noticeTimer = setInterval(() => {
			currentNoticeIndex.value = (currentNoticeIndex.value + 1) % noticeList.value.length
		}, 3000)
	}
	const goToNotice = (noticeId) => {
		uni.navigateTo({
			url: `/pages/notice/notice?noticeId=${noticeId}`
		})
	}
	// 检查登录状态
	const checkLoginStatus = () => {
		// 登录状态检查逻辑
	}

	// 快捷图标点击事件
	const handleQuickAction = (action) => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}

		switch (action) {
			case 'schedule':
				uni.navigateTo({
					url: '/pages/schedule/schedule'
				})
				break
			case 'health':
				uni.showToast({
					title: '健康管理开发中',
					icon: 'none'
				})
				break
			case 'analysis':
				uni.showToast({
					title: '数据分析开发中',
					icon: 'none'
				})
				break
			case 'foster':
				uni.showToast({
					title: '寄养服务开发中',
					icon: 'none'
				})
				break
			default:
				break
		}
	}

	// 打开帖子详情
	const openPostDetail = (post) => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}

		console.log('Open post:', post.postId)
		uni.navigateTo({
			url: `/pages/post-detail/post-detail?id=${post.postId}`
		})
	}

	// 评论按钮点击
	const handleComment = (post) => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}

		uni.navigateTo({
			url: `/pages/post-detail/post-detail?id=${post.postId}`
		})
	}

	// 跳转至发布帖子页面
	const navigateToAddPost = () => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}

		uni.navigateTo({
			url: '/pages/post-detail/add/add-post'
		})
	}

	// 查看用户资料
	const viewUserProfile = (userId) => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}
		console.log('View user profile:', userId)
		uni.navigateTo({
			url: `/pages/user-profile/user-profile?userId=${userId}`
		})
	}

	// 回到顶部
	const handleScrollToTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		})
	}
</script>

<style scoped>
	.home-page {
		min-height: 100vh;
		background-color: #F5F5F5;
		padding-bottom: 120rpx;
		box-sizing: border-box;
	}

	/* Banner */
	.banner-swiper {
		width: 100%;
		height: 400rpx;
	}

	.swiper {
		width: 100%;
		height: 100%;
	}

	.banner-image {
		width: 100%;
		height: 100%;
	}

	/* 公告栏样式 */
	.notice-bar {
		width: calc(100% - 64rpx);
		margin: 0 32rpx 24rpx;
		height: 80rpx;
		width: 643rpx;
		background-color: #FFF8E6;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		overflow: hidden;
		position: relative;
	}

	.notice-icon {
		font-size: 32rpx;
		margin-right: 16rpx;
		color: #FF9800;
		flex-shrink: 0;
	}

	.notice-content {
		height: 100%;
		transition: transform 0.5s ease;
	}

	.notice-item {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #E65100;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	/* 快捷图标 */
	.quick-icons {
		display: flex;
		justify-content: space-around;
		padding: 40rpx 32rpx;
		background-color: #FFFFFF;
		margin: 0 32rpx 24rpx;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.icon-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.icon-circle {
		width: 96rpx;
		height: 96rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 16rpx;
		font-size: 48rpx;
	}

	.icon-text {
		font-size: 24rpx;
		color: #5A7D9A;
	}

	/* 帖子列表 */
	.post-list {
		padding: 0 32rpx;
	}

	.post-card {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		overflow: hidden;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.post-image-container {
		position: relative;
		width: 100%;
	}

	.single-image {
		width: 100%;
		height: 400rpx;
	}

	.post-image {
		width: 100%;
		height: 100%;
	}

	.ai-badge {
		position: absolute;
		top: 16rpx;
		left: 16rpx;
		background-color: rgba(137, 207, 240, 0.8);
		color: #FFFFFF;
		padding: 8rpx 16rpx;
		border-radius: 999rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
	}

	.badge-text {
		margin-left: 8rpx;
	}

	.post-info {
		padding: 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.user-info {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.avatar {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		margin-right: 16rpx;
	}

	.user-detail {
		display: flex;
		flex-direction: column;
	}

	.username {
		font-size: 28rpx;
		font-weight: 500;
		color: #333333;
	}

	.post-time {
		font-size: 24rpx;
		color: #999999;
		margin-top: 4rpx;
	}

	.post-actions {
		display: flex;
		gap: 32rpx;
	}

	.action-item {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #999999;
	}

	.action-text {
		margin-left: 8rpx;
	}

	.title-info {
		font-size: 36rpx;
		margin: 16rpx;
		display: block;
		color: #333;
	}

	/* 悬浮按钮 */
	.float-extra-btn {
		position: fixed;
		right: 32rpx;
		bottom: calc(130rpx + var(--safe-area-inset-bottom));
		width: 90rpx;
		height: 90rpx;
		background-color: #89CFF0;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #FFFFFF;
		box-shadow: 0 8rpx 24rpx rgba(255, 209, 220, 0.4);
		z-index: 999;
	}
 
	.float-add-btn {
		position: fixed;
		right: 32rpx;
		bottom: calc(20rpx + var(--safe-area-inset-bottom));
		width: 90rpx;
		height: 90rpx;
		background-color: #89CFF0;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #FFFFFF;
		box-shadow: 0 8rpx 24rpx rgba(137, 207, 240, 0.4);
		z-index: 999;
	}
</style>